package com.zfl;


import lombok.ToString;

@ToString
public class Trie {

    public static void main(String[] args) {
        Trie trie = new Trie();
        System.out.println("trie = " + trie);
        trie.insert("ac");
        System.out.println("trie.search(\"ac\") = " + trie.search("ac"));
    }


//    @ToString
    private static class TrieNode{
        TrieNode[] children;
        boolean isEnd;

        public TrieNode() {
            this.children = new TrieNode[26];
            this.isEnd=false;
        }
    }

    private final TrieNode root;


    public Trie() {
        this.root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = this.root;
        for (char c : word.toCharArray()) {
            int index = c-'a';
            if (node.children[index]==null) {
                node.children[index] = new TrieNode();
            }
            node = node.children[index];
        }
        node.isEnd = true;

    }

    public boolean search(String word) {
        TrieNode node = this.root;
        for (char c : word.toCharArray()) {
            int index = c-'a';
            if (node.children[index]==null) {
                return false;
            }
            node = node.children[index];
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        TrieNode node  = this.root;
        for (char c : prefix.toCharArray()) {
            int index = c-'a';
            if(node.children[index]==null) {
               return false;
            }
            node = node.children[index];
        }
        return true;
    }
}
